<script setup lang="ts">
import { NumberSlider } from "@/models/reactiveComponent";
import { computed, ref, watch, inject } from "vue";
import * as injectKeys from "@/services/injectKeys";

const props = defineProps<{ model: NumberSlider }>();
const model = props.model;

const dbServices = inject(injectKeys.dbKey)!;
const reactdataServices = inject(injectKeys.reactdataServicesKey)!;

const filterHandler = reactdataServices.getFilterHandler(model);

const appEventService = inject(injectKeys.appEventServiceKey)!;
const utilsService = inject(injectKeys.utilsKey)!;

appEventService.onResetFilters(() => {
  input.value = model.initValue ?? initValue;
});

let hasRange = false;
if ("range" in model.props) {
  hasRange = model.props.range;
}

function getBounds() {
  const table = model.updateInfos[0].table;
  const field = model.updateInfos[0].field;

  const query = utilsService.createSqlQuery(
    model.id,
    `select min(${field}) as min,max(${field}) as max from ${table}`
  );

  // const query = dbServices.queryAll(
  //   `select min(${field}) as min,max(${field}) as max from ${table}`
  // );

  const row = query.query().rows[0];
  return [row.min, row.max];
}

const bounds = getBounds();

const initValue = hasRange ? bounds : bounds[0];

const input = ref(model.initValue ?? initValue);
watch(input, (value) => {
  let expr = "";
  if (typeof value === "number") {
    expr = model.whereExpr.replaceAll("${}", value.toString());
  } else if (Array.isArray(value)) {
    expr = model.whereExpr
      .replaceAll("${0}", value[0].toString())
      .replaceAll("${1}", value[1].toString());
  }

  filterHandler.addFilter(expr);
});

const cpProps = { min: bounds[0], max: bounds[1], ...model.props };
</script>

<template>
  <div class="pybi-input" data-pybi-auto-width>
    <el-slider v-model="input" v-bind="cpProps" />
  </div>
</template>

<style scoped lang="less">
.pybi-input {
  // width: 18em;
  min-width: 15em;
  width: 100%;
}
</style>
